﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _11_Task_后继线程
{
    internal class Program
    {
        static Random rd = new Random();

        static void Main(string[] args)
        {
            Console.WriteLine("[{0}] 主线程开始执行",DateTime.Now);

            Task<int> task = new Task<int>(() => ComputeSum(100));
            task.Start();
            //规定task执行完毕后的后继任务
            task.ContinueWith(result =>
            {
                Console.WriteLine("计算结果是：" + result.Result);
            });

            Console.Read();
        }

        /// <summary>
        /// 累加计算
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static int ComputeSum(int n)
        {
            int sum  =0;
            for (int i = 0; i < n; i++)
            {
                sum += i;
                Thread.Sleep(rd.Next(1,100));//1-100 模拟计算耗时
            }
            Console.WriteLine("计算完成");
            return sum;
        }

    }
}
